/*
*  Copyright (c) 2001 Sun Microsystems, Inc.  All rights
*  reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*  1. Redistributions of source code must retain the above copyright
*  notice, this list of conditions and the following disclaimer.
*
*  2. Redistributions in binary form must reproduce the above copyright
*  notice, this list of conditions and the following disclaimer in
*  the documentation and/or other materials provided with the
*  distribution.
*
*  3. The end-user documentation included with the redistribution,
*  if any, must include the following acknowledgment:
*  "This product includes software developed by the
*  Sun Microsystems, Inc. for Project JXTA."
*  Alternately, this acknowledgment may appear in the software itself,
*  if and wherever such third-party acknowledgments normally appear.
*
*  4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA"
*  must not be used to endorse or promote products derived from this
*  software without prior written permission. For written
*  permission, please contact Project JXTA at http://www.jxta.org.
*
*  5. Products derived from this software may not be called "JXTA",
*  nor may "JXTA" appear in their name, without prior written
*  permission of Sun.
*
*  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
*  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*  DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
*  ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
*  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
*  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
*  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
*  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*  SUCH DAMAGE.
*  ====================================================================
*
*  This software consists of voluntary contributions made by many
*  individuals on behalf of Project JXTA.  For more
*  information on Project JXTA, please see
*  <http://www.jxta.org/>.
*
*  This license is based on the BSD license adopted by the Apache Foundation.
*
*  $Id: PeerProfileAction.java,v 1.7 2007/01/26 21:54:32 bondolo Exp $
*/

package net.jxta.myjxta.ui.action;

import net.jxta.logging.Logging;
import net.jxta.myjxta.View;
import net.jxta.myjxta.dialog.DialogMessage;
import net.jxta.myjxta.dialog.commands.ProfileCommand;
import net.jxta.myjxta.dialog.util.RemoteCommandInvoker;
import net.jxta.myjxta.util.Group;
import net.jxta.myjxta.util.Peer;
import net.jxta.myjxta.util.Resources;
import net.jxta.myjxta.util.objectmodel.GroupNode;
import net.jxta.myjxta.util.objectmodel.PeerNode;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author james todd [gonzo at jxta dot org]
 * @version $Id: PeerProfileAction.java,v 1.7 2007/01/26 21:54:32 bondolo Exp $
 */

public class PeerProfileAction
        extends AbstractAction {

    private static final int INTERVAL = 250;
    private static final int MAX = INTERVAL * 4 * 20;
    private static final ResourceBundle STRINGS = Resources.getStrings();

    private static final Logger LOG = Logger.getLogger(PeerProfileAction.class.getName());

    private View view = null;

    public PeerProfileAction(String name, View view) {
        super(name);

        this.view = view;

        if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) {
            LOG.info("PeerStatusAction instantiated");
        }
    }

    public boolean isEnabled() {
        PeerNode jxtaNode = (PeerNode) view.getJxtaNode(PeerNode.class);
        return jxtaNode != null;
    }

    public void actionPerformed(ActionEvent ae) {
        PeerNode pn = (PeerNode) this.view.getJxtaNode(PeerNode.class);
        final Peer p = pn != null ? pn.getPeer() : null;
        final Group g = pn != null ?
                ((GroupNode) (pn.getParent())).getGroup() : null;
        String status = null;

        if (p != null &&
                g != null) {
            status = STRINGS.getString("status.command.initiate") + ": " +
                    p.getName();

            if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) {
                LOG.info(status);
            }

            new Thread(new Runnable() {
                public void run() {
                    process(g, p);
                }
            }, getClass().getName() + ":getConnection").start();
        } else {
            String peerName = "null";

            if (p != null) {
                peerName = p.getName();
            }

            status = STRINGS.getString("error.peer.invalid") + " " + peerName;


            if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) {
                LOG.severe(status);
            }
        }

        if (status != null) {
            this.view.setStatus(status);
        }
    }

    private void process(Group g, Peer p) {
        String status = STRINGS.getString("status.peer.profile.request") +
                p.getName();

        this.view.setStatus(status);

        if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) {
            LOG.info(status);
        }

        if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) {
            LOG.info(status);
            LOG.info("instantiating ProfileCommand");
        }

        RemoteCommandInvoker cf = new RemoteCommandInvoker(g, p.getPipeAdvertisement(),
                new ProfileCommand(), this.view.getControl());

        if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) {
            LOG.info("dispatch command");
        }

        cf.invoke(MAX);

        DialogMessage r = cf.getResponse();

        if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) {
            LOG.info("ProfileCommand response: " + r);
        }

        String res = r != null ? r.getCommand() : null;

        if (res != null) {
            status = STRINGS.getString("status.peer.profile.process") + ": "
                    + p.getName();

            this.view.setStatus(status);

            if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) {
                LOG.info(status);
            }

//            Resource rs = new Resource();
//
//            try {
//                rs.load(new ByteArrayInputStream(res.getBytes()));
//            } catch (ResourceNotFoundException rnfe) {
//                rnfe.printStackTrace();
//            }        
//            
//            StringBuffer sb = new StringBuffer(rs.get("/response"));
            StringBuffer sb = new StringBuffer(res);

            if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) {
                LOG.fine(sb.toString());
            }

            JDialog jd = new JDialog((JFrame) this.view,
                    STRINGS.getString("title.peer"), false);

            jd.getContentPane().add(new JScrollPane(new JTextArea(sb.toString())));
            jd.pack();
            jd.setLocationRelativeTo((JFrame) this.view);
            jd.setVisible(true);

            p = null;
            jd = null;
        } else {
            status = STRINGS.getString("error.peer.profile") + ": " +
                    p.getName();

            this.view.setStatus(status);

            if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) {
                LOG.info("bad response: " + status);
            }
        }
    }
}
